import requests;
import json;
import re;
import mysql.connector;
import datetime
# import pandas as pd
# import numpy as np
import time
# from datetime import datetime
from tqdm import tqdm
import byrg;
class cc():

	def getCC(self,a):


		file='../phpstudy_pro/WWW/cscs.qumei.com/weizanZB/cc/cc.json'
		with open(file,'w',encoding='utf-8') as f:
			json.dump(a,f,ensure_ascii=False)
			str="加载入文件完成..."

		print('结束')


	def getRequCC(self,pageIndex=0,FromDate = time.strftime("%Y-%m-%d", time.localtime()),ToDate = time.strftime("%Y-%m-%d", time.localtime())):


		searchJson=json.dumps({"FromDate":FromDate,"ToDate":ToDate,"ChannelID":-1,"IsTaskStatus":1,"IsDeleted":0,"IsCommunicateStatistics":1})

		url_params={'pageIndex':pageIndex,'searchJson':searchJson}

		r=requests.get(
			'http://cc.qumei.com/TaskManage/GetCommunicateStatisticsList'
			,params=url_params
			,timeout=60
			);

		txt=r.text

		patternCount = re.compile(r'"TotalItems":\d+|"TotalPages":\d+|"PageSize":\d+')   # 检索总条目数和总页数

		Countresult1 = patternCount.findall(txt)

		TotalItems = re.sub(r'\D+','',Countresult1[0])

		TotalPages = re.sub(r'\D+','',Countresult1[1])

		PageSize = re.sub(r'\D+','',Countresult1[2])

		p=re.search(r'\[.*\]',txt) #检索内部data

		data=p.group()

		data=re.sub(r'\\','',data)

		# print(data)

		pattern =r'(?<=CommunicateContent":").*?(?=",)'

		

		# self.getCC(data)

		datalist=json.loads(data)

		result = {'TotalItems':TotalItems,'TotalPages':TotalPages,'pageIndex':pageIndex,'PageSize':PageSize,'datalist':datalist}
	

		return result

	def ccup(self,FromDate=time.strftime("%Y-%m-%d",time.localtime()),ToDate=time.strftime("%Y-%m-%d",time.localtime())):


		ccres = self.getRequCC(pageIndex=0,FromDate = FromDate,ToDate = ToDate)

		TotalPages =ccres['TotalPages']

		print('TotalPages=>',TotalPages)

		ccreslist=[]

		for i in tqdm(range(0,int(TotalPages)-1)):#5301-5303 #6218-6220 #6570 #int(TotalPages)-1)

			# print(i)

			ccresItem = self.getRequCC(pageIndex=i,FromDate = FromDate,ToDate = ToDate)

			# print(ccresItem['datalist'])

			# ccreslist.extend(ccresItem['datalist'])

			self.upDbcc(ccresItem['datalist'],'ccTable')


		# print('count=>',len(ccreslist))


	def upDbcc(self,datelist,tableName):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)


		mycursor = mydb.cursor()
		upCount=0
		for item in datelist:

			val=[]
			filed=[]
			for key in item:
				filed.append(key)
				val.append('\"'+str(item[''+key+''])+'\"')

			filedStr=','.join(filed)
			valStr=','.join(val)
			# print(item['adv_id'])

			sql="replace into " + tableName + "("+filedStr+")value("+valStr+")"
			# print('SQL=>',sql)
			mycursor.execute(sql)
			upCount=upCount+int(mycursor.rowcount)
			mydb.commit()
		mydb.close()

		return upCount


	def getYouju(self,maxPage):


		for i in range(1,maxPage):

			#print('i=:',i)

			url_params={'page':i,'key':''}

			headers={'Cookie':'PHPSESSID=qcc79d1fcb1atbsh4e6qjgq8pk'}
			# admin
			# a123a123
			r=requests.get(
				'http://home.243000.net/admin/banner/index.html'
				,params=url_params
				,headers=headers
				);

			txt=r.text

			# print('getyouju==>',txt)
			# return
			listdate=json.loads(txt);

			if len(listdate) > 0 :

				print('upCount=:',self.upDb(listdate,'youjuTell'))

	def upDb(self,datelist,tableName):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)

		mycursor = mydb.cursor()
		upCount=0
		for item in datelist:

			val=[]
			filed=[]
			for key in item:
				filed.append(key)
				val.append('\"'+str(item[''+key+''])+'\"')

			filedStr=','.join(filed)
			valStr=','.join(val)
			# print(item['adv_id'])
			if tableName == "zhuandanphone":
				sql="REPLACE INTO " + tableName + "("+filedStr+")value("+valStr+")"
			else:
				sql="INSERT ignore into " + tableName + "("+filedStr+")value("+valStr+")"
			# print(sql)
			mycursor.execute(sql)
			upCount=upCount+int(mycursor.rowcount)
			mydb.commit()
		mydb.close()

		return upCount



	def getZhuanDan(self,PageSize):

		endCallTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S');

		startCallTime=(datetime.datetime.now()-datetime.timedelta(hours=6)).strftime('%Y-%m-%d %H:%M:%S')

		# endCallTime = "2021-05-17 23:59:59"

		# startCallTime = "2021-05-17 12:59:59"

		# print(startCallTime,endCallTime)

		wher=json.dumps({'FromDate':startCallTime,'ToDate':endCallTime,'KeyWord':'','ChannelID':'','ConsultantName':''});

		data={'SqlWhere':wher,'PageNum':'0',"PageSize":PageSize};

		a=requests.post(url='http://go.qumei.com/api/CRM/CustomerDataDetail',data=json.dumps(data),timeout=60);

		data=json.loads(a.text)['Data']

		totalCount=data['TotalCount'];

		datalist=data['Data'];


		PageNum=round(totalCount/PageSize)+1


		if PageNum > 1 :

			listI=[]

			for i in range(0,PageNum):

				data={'SqlWhere':wher,'PageNum':i,"PageSize":PageSize};

				a=requests.post(url='http://go.qumei.com/api/CRM/CustomerDataDetail',data=json.dumps(data),timeout=60);

				data=json.loads(a.text)['Data']

				datalist=data['Data'];

				listI.extend(datalist)
		else:

			listI = datalist




		return self.upDb(listI,'zhuandanphone')
		# print('转单==>',self.upDb(listI,'zhuandanphone'))

	def sleeptime(self,hour,min,sec):
		return hour*3600 + min*60 + sec;

	def tijiaoCC(self):


		url = 'http://49.233.122.9/cc/callCC.php?type=1';
		parmas = {'type':'1'};

		r = requests.get(url = url,data = json.dumps(parmas) ,timeout=60);

		print(r.text)

if __name__ == '__main__':

	cc=cc()

	cc.getYouju(10)

	print('转单==》',cc.getZhuanDan(20))

	# cc.tijiaoCC()

	cc.ccup(time.strftime("%Y-%m-%d"),time.strftime("%Y-%m-%d")) #'2020-08-29','2020-08-31'

	second = cc.sleeptime(0,0,30);

	while 1 == 1:

		time.sleep(second)

		hour =int(time.strftime("%H"))

		if(hour < 21 and hour > 8  ):

			try:
				print('转单==>',cc.getZhuanDan(20))
				cc.ccup(time.strftime("%Y-%m-%d"),time.strftime("%Y-%m-%d")) #'2020-08-29','2020-08-31'
				cc.getYouju(10)
				# cc.tijiaoCC()
			except:
				print('erro')